<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>js 模糊查询树形结构数据并返回其所有上级节点(只搜索最后一层)</title>
  <script src="./treeData.js"></script>
</head>

<body>
  <script>
    let arr = [
      {
        title: '你好吗？',
        children: [
          {
            title: '很好啊',
            children: null
          },
          {
            title: '是吗',
            children: [{
              title: '非常好芬层1',
              children: null
            }, {
              title: '第-非常好芬2',
              children: null
            }, {
              title: '第三层3',
              children: null
            }]
          }
        ]
      },
      {
        title: '卡卡卡',
        children: [
          {
            title: '非常好芬',
            children: null
          }
        ]
      },
      {
        title: '第三方的',
        children: null
      }
    ];

    // 搜索树结构, 深度搜索(只对最底层内容搜索)
    const rebuildData = (value, arr = []) => {
      let newarr = [];
      arr.forEach(element => {
        if (element.children && element.children.length) {
          const ab = rebuildData(value, element.children);
          const obj = {
            ...element,
            children: ab
          };
          if (ab && ab.length) {
            newarr.push(obj);
          }
        } else {
          // 无子元素功能
          if (element.name.indexOf(value) > -1) {
            newarr.push(element);
          }
        }
      });
      return newarr;
    };
    console.log('搜索-书 ===', rebuildData('书', treeData));
    console.log('搜索-电影 ===', rebuildData('电影', treeData));
  </script>
</body>

</html>